<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary" @click="openCateDialog">添加分类</el-button>
                </el-col>
            </el-row>
            <tree-table
                :data="cateList"
                :columns="columns"
                :selection-type="false"
                :expand-type="false"
                :show-row-hover="false"
                show-index
                border
                class="tree-table"
            >
                <template v-slot:status="scope">
                    <i class="el-icon-success" v-if=" scope.row.cat_deleted === false "></i>
                    <i class="el-icon-error" v-else></i>
                </template>
                <template v-slot:level="scope">
                    <el-tag size="mini" v-if=" scope.row.cat_level === 0 ">一级</el-tag>
                    <el-tag size="mini" type="success" v-else-if=" scope.row.cat_level === 1 ">二级</el-tag>
                    <el-tag size="mini" type="warning" v-else>三级</el-tag>
                </template>
                <template v-slot:opt="scope">
                    <el-button
                        type="primary"
                        size="mini"
                        icon="el-icon-edit"
                        @click="openCateDialog(scope.row)"
                    >编辑</el-button>
                    <el-button
                        type="danger"
                        size="mini"
                        icon="el-icon-delete"
                        @click="deleteCate(scope.row)"
                    >删除</el-button>
                </template>
            </tree-table>
            <!-- 分页 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="pageSizes"
                :page-size="queryInfo.pagesize"
                :layout="pageLayout"
                :total="total"
                background
            ></el-pagination>
        </el-card>
        <!-- 分类添加/修改窗口 -->
        <el-dialog
            :title="cateTitle"
            :visible.sync="cateDialogVisible"
            width="50%"
            @close="cateDialogClose"
        >
            <el-form :model="cateForm" :rules="cateFormRules" ref="cateFormRef" label-width="100px">
                <el-form-item label="分类名称" prop="cat_name">
                    <el-input v-model="cateForm.cat_name"></el-input>
                </el-form-item>
                <el-form-item label="父级分类" v-if="cateForm.cat_id === 0">
                    <el-cascader
                        ref="parentCateRef"
                        v-model="parentSelectValues"
                        :options="parentCateList"
                        :props="parentCateProps"
                        @change="parentCateChange"
                        clearable
                    ></el-cascader>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cateDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveCate">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import config from '@/util/config'
export default {
    data() {
        return {
            queryInfo: {
                type: 3,
                pagenum: config.pageNum,
                pagesize: config.pageSize
            },
            pageSizes: config.pageSizes,
            pageLayout: config.pageLayout,
            cateList: [],
            total: 0,
            columns: [
                { label: '分类名称', prop: 'cat_name' },
                { label: '是否启用', type: 'template', template: 'status' },
                { label: '分类等级', type: 'template', template: 'level' },
                { label: '操作', type: 'template', template: 'opt' }
            ],
            cateDialogVisible: false,
            cateForm: {
                cat_id: 0,
                cat_name: '',
                cat_pid: 0,
                cat_level: 0
            },
            cateFormRules: {
                cat_name: [
                    { required: true, message: '请输入分类名称', trigger: 'blur' }
                ]
            },
            parentCateList: [],
            parentSelectValues: [],
            parentCateProps: {
                checkStrictly: true,
                expandTrigger: 'hover',
                value: 'cat_id',
                label: 'cat_name',
                children: 'children'
            },
            cateTitle: ''
        }
    },
    methods: {
        // 列表数据
        async getCateList() {
            const { data: res } = await this.$http.get('categories', {
                params: this.queryInfo
            })
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.cateList = res.data.result
            this.total = res.data.total
        },
        // 监听 pagesize 改变
        handleSizeChange(newSize) {
            this.queryInfo.pagesize = newSize
            this.getCateList()
        },
        // 监听 pagenum 改变
        handleCurrentChange(newPage) {
            this.queryInfo.pagenum = newPage
            this.getCateList()
        },
        // 打开添加/编辑分类窗口
        async openCateDialog(cateInfo) {
            this.getParentCateList()
            this.cateDialogVisible = true
            if (cateInfo.cat_id > 0) {
                this.cateTitle = '编辑分类'
                const { data: res } = await this.$http.get('categories/' + cateInfo.cat_id)
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                this.cateForm = res.data
            } else {
                this.rolesTitle = '添加分类'
            }
        },
        // 得到父级分类数据列表
        async getParentCateList() {
            const { data: res } = await this.$http.get('categories', {
                params: { type: 2 }
            })
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.parentCateList = res.data
        },
        // 监听父级分类cascader选择项变化
        parentCateChange() {
            if (this.parentSelectValues.length > 0) {
                this.cateForm.cat_pid = this.parentSelectValues[this.parentSelectValues.length - 1]
                this.cateForm.cat_level = this.parentSelectValues.length
                return
            } else {
                this.cateForm.cat_pid = this.cateForm.cat_level = 0
            }
        },
        // 保存分类信息
        saveCate() {
            this.$refs.cateFormRef.validate(async valid => {
                if (!valid) return
                // 编辑分类信息
                if (this.cateForm.cat_id > 0) {
                    const { data: res } = await this.$http.put('categories/' + this.cateForm.cat_id, this.cateForm)
                    if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                    this.$message.success(res.meta.msg)
                } else {    // 添加分类信息
                    const { data: res } = await this.$http.post('categories', this.cateForm)
                    if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
                    this.$message.success(res.meta.msg)
                }
                this.getCateList()
                this.cateDialogVisible = false
            })
        },
        // 监听添加用户窗口关闭，并重置表单
        cateDialogClose() {
            this.$refs.cateFormRef.resetFields()
            this.parentSelectValues = []
            this.cateForm.cat_id = 0
            this.cateForm.cat_pid = 0
            this.cateForm.cat_level = 0
        },
        // 删除分类信息
        async deleteCate(cateInfo) {
            const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                type: 'warning'
            }).catch(err => err)
            if(confirmRes !== 'confirm') return
            const { data: res } = await this.$http.delete('categories/' + cateInfo.cat_id)
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.$message.success(res.meta.msg)
            let currentPageNum = this.total - (this.queryInfo.pagenum * this.queryInfo.pagesize)
            if(currentPageNum <= 0) {
                this.queryInfo.pagenum = this.queryInfo.pagenum - 1
            }
            this.getCateList()
        }
    },
    created() {
        this.getCateList()
    },
    watch: {
        // 监听cascader选择项值发生变化就关闭
        parentSelectValues: {
            handler(newVal, oldVal) {
                if (this.$refs.parentCateRef) {
                    // var children = this.$refs.parentCateRef.getCheckedNodes();
                    // 判断有没有下级
                    // if (children[0].children.length < 1) {
                    this.$refs.parentCateRef.dropDownVisible = false
                    // }
                }
            }
        }
    }
}
</script>

<style lang="less" scoped>
.tree-table {
    margin-top: @default-margin;
    .el-icon-success {
        color: @green;
        font-size: 16px;
    }
    .el-icon-error {
        color: @red;
        font-size: 16px;
    }
}
.el-cascader {
    width: 100%;
}
</style>